package hust.iamk.backup;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;

public class ImageDownloader extends AsyncTask<String, Integer, Bitmap> {
	private FileOutputStream fos;
	Context context;
	boolean LOAD_FILE = true;

	@Override
	protected Bitmap doInBackground(String... urls) {
		// TODO Auto-generated method stub
		String urldisplay = urls[0];
		Bitmap mIcon11 = null;
		int count;
		try {
			URL url = new URL(urldisplay);
			URLConnection urlConnection = url.openConnection();
			urlConnection.setConnectTimeout(300000);
			urlConnection.connect();

			InputStream inputStream = new BufferedInputStream(url.openStream());
			File file = new File(
					Environment.getExternalStorageDirectory()
							+ File.separator
							+ "Pictures"
							+ File.separator
							+ "iamk"
							+ File.separator
							+ urldisplay.split("/")[urldisplay.split("/").length - 1]
									.split(Pattern.quote("?"))[0]);

			OutputStream outputStream = new FileOutputStream(file);

			byte data[] = new byte[1024];

			while ((count = inputStream.read(data)) != -1) {
				// total += count;
				// publishProgress((int) ((total * 100) / lenghtImage));
				outputStream.write(data, 0, count);
			}

			outputStream.flush();
			outputStream.close();
			inputStream.close();

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.ARGB_8888;
			mIcon11 = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
			LOAD_FILE = true;
		} catch (Exception e) {
			LOAD_FILE = false;
			Log.e("Error", e.getMessage());
			e.printStackTrace();
		}
		return mIcon11;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}

	@Override
	protected void onPostExecute(Bitmap result) {
	}

}
